/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.mochaccino.framework.rest.resources;

import com.google.common.base.Preconditions;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class ResourceFile implements Resource {
	private List<URL> urls      = new ArrayList<URL>();
	private Logger    logger    = LoggerFactory.getLogger( getClass() );
	private boolean   recursive = false;

	public ResourceFile( File resource, boolean recursive ) {
		Preconditions.checkNotNull( resource );
		this.recursive = recursive;
		if ( resource.isFile() && resource.canRead() ) {
			addFile( resource );
		} else if ( resource.isDirectory() && resource.canRead() ) {
			addDirectory( resource );
		}
	}

	public static final ResourceFile non_recursive( File file ) {
		return new ResourceFile( file, true );
	}

	public static final ResourceFile recursive( File file ) {
		return new ResourceFile( file, true );
	}

	private void add( File resource ) {
		if ( resource.isFile() && resource.canRead() ) {
			addFile( resource );
		} else if ( resource.isDirectory() && resource.canRead() && recursive ) {
			addDirectory( resource );
		}
	}

	private void addDirectory( File resource ) {
		for ( File f : resource.listFiles() ) {
			add( f );
		}
	}

	private void addFile( File resource ) {
		try {
			urls.add( resource.toURI().toURL() );
		} catch ( MalformedURLException e ) {
			logger.error( e.getMessage(), e );
		}
	}

	@Override
	public URL[] getURLs() {
		return urls.toArray( new URL[urls.size()] );
	}
}
